﻿using FluentNHibernate.Mapping;

namespace WSKnowledge.WSHelpers.NHibernate
{
	public class EntityMap<TEntity> : ClassMap<TEntity>
		where TEntity : IEntity<TEntity>
	{
		private const string RowVerionColumnName = "ROW_VERSION";

		protected EntityMap()
		{
			AutoImport();
			LazyLoad();
			WithTable(GetTableName());
			OptimisticLock.Version();
			DefaultAccess.AsReadOnlyPropertyThroughCamelCaseField(Prefix.Underscore);

			Id(p => p.Id)
				.GeneratedBy.Sequence(GetSequenceName())
				.ColumnName(GetIDColumn())
				.WithUnsavedValue(0);


			Version(p => p.Version)
				.ColumnName(RowVerionColumnName);
		}

		protected string GetTableName()
		{
			return TableName ?? typeof(TEntity).Name.AsOracleCase();
		}

		protected string GetIDColumn()
		{
			return "ID_" + GetTableName();
		}

		protected string GetSequenceName()
		{
			return "SEQ_" + GetTableName();
		}

		protected string GetUniqueKeyFor(string propertyName)
		{
			return "UK_" + GetTableName() + "_" + propertyName.AsOracleCase();
		}

		protected static string GetTableName<T>()
		{
			return typeof(T).Name.AsOracleCase();
		}

		protected static string GetIDColumn<T>()
		{
			return "ID_" + GetTableName<T>();
		}

		protected static string GetForeignKeyName<TChild, TParent>(int order)
		{
			return "FK_" + GetTableName<TChild>() + "_" + GetTableName<TParent>() + order;
		}
	}
}
